package com.yy.young.ums.service.impl;

import com.yy.young.interfaces.model.User;
import com.yy.young.common.util.CommonUtil;
import com.yy.young.common.util.StringUtils;
import com.yy.young.dal.service.IDataAccessService;
import com.yy.young.dal.util.Page;
import com.yy.young.ums.service.*;
import com.yy.young.ums.util.SecureHandler;
import com.yy.young.ums.util.UmsConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ums用户服务实现
 * Created by Administrator on 2017/5/8.
 */
@Service("umsUserService")
public class UmsUserServiceImpl implements IUmsUserService {

    @Resource(name="dataAccessService")
    IDataAccessService dataService;

    @Resource(name="umsDeptService")
    IUmsDeptService deptService;

    @Resource(name="umsRoleService")
    IUmsRoleService roleService;

    @Resource(name = "umsRoleUserService")
    IUmsRoleUserService umsRoleUserService;

    @Resource(name = "umsDeptUserService")
    IUmsDeptUserService umsDeptUserService;

    private static final Logger logger = LoggerFactory.getLogger(UmsUserServiceImpl.class);

    @Override
    public List<Map<String, Object>> getUserList(Map<String, Object> parameter) throws Exception {
        return dataService.getList(UmsConstants.MAPPER.UMS_USER+".getUser",parameter);
    }

    @Override
    public List<Map<String, Object>> getUserPage(Map<String, Object> parameter,Page page) throws Exception {
        return dataService.getList(UmsConstants.MAPPER.UMS_USER+".getUser",parameter,page);
    }

    @Override
    public int updateUser(Map<String, Object> parameter) throws Exception {
        if (parameter.containsKey("PASSWORD") && parameter.get("PASSWORD") != null){//如果要修改密码,则进行加密
            parameter.put("PASSWORD", SecureHandler.encrypt(parameter.get("PASSWORD")+""));
        }
        return dataService.update(UmsConstants.MAPPER.UMS_USER+".updateUser",parameter);
    }

    @Override
    public int updateUser(User user) throws Exception {
        if (user.getPassword() != null){//当密码不为null时,对密码进行加密
            user.setPassword(SecureHandler.encrypt(user.getPassword()));
        }
        return dataService.update(UmsConstants.MAPPER.UMS_USER+".updateUserObj", user);
    }

    @Override
    public int deleteUser(Map<String, Object> parameter) throws Exception {
        String idsStr = parameter.get("ids")+"";
        if(StringUtils.isNotBlank(idsStr)){
            String[] idsArr = idsStr.split(",");
            parameter.put("ids",idsArr);
            //删除用户相关的关联信息
            if(idsArr != null && idsArr.length > 0){
                for (String uid : idsArr){
                    logger.info("[删除用户] 擦除用户({})相关的角色/部门关联!", uid);
                    //删除用户角色
                    umsRoleUserService.deleteRoleUserByUserId(uid);
                    //用户部门
                    umsDeptUserService.deleteDeptUserByUserId(uid);
                }
            }
        }
        return dataService.delete(UmsConstants.MAPPER.UMS_USER+".deleteUser",parameter);
    }

    @Override
    public int deleteUser(String userId) throws Exception {
        Map<String, Object> parameter = new HashMap<String, Object>();
        parameter.put("ids", userId);
        //调用服务deleteUser(Map<String, Object> parameter)进行删除
        return this.deleteUser(parameter);
    }

    @Override
    public int insertUser(Map<String, Object> parameter) throws Exception {
        if(StringUtils.isBlank(parameter.get("ID") + "")){
            parameter.put("ID", CommonUtil.getUUID());//默认ID为UUID
        }
        parameter.put("PASSWORD", SecureHandler.encrypt(UmsConstants.DEFAULT.USER_PASSWORD));//默认初始密码
        //如果单位为空,则设置"无单位"
        if (StringUtils.isBlank(parameter.get("COMPANY_ID") + "")){
            parameter.put("COMPANY_ID", UmsConstants.DEFAULT.NOT_COMPANY);
        }
        return dataService.insert(UmsConstants.MAPPER.UMS_USER+".insertUser",parameter);
    }

    //插入用户
    @Override
    public int insertUser(User user) throws Exception {
        if (StringUtils.isBlank(user.getId())){//默认id为uuid
            user.setId(CommonUtil.getUUID());
        }
        //如果密码不为空,则对密码进行加密,否则设置默认密码
        if (StringUtils.isNotBlank(user.getPassword())){
            user.setPassword(SecureHandler.encrypt(user.getPassword()));
        }else{
            user.setPassword(SecureHandler.encrypt(UmsConstants.DEFAULT.USER_PASSWORD));
        }
        //如果单位为空,则设置"无单位"
        if (StringUtils.isBlank(user.getCompanyId())){
            user.setCompanyId(UmsConstants.DEFAULT.NOT_COMPANY);
        }
        return dataService.insert(UmsConstants.MAPPER.UMS_USER+".insertUserObj", user);
    }

    @Override
    public User getUserByAccount(String account) throws Exception {
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("account",account);
        return (User) dataService.getObject(UmsConstants.MAPPER.UMS_USER+".getUserByAccount",map);
    }

    @Override
    public int resetPassword(String ids) throws Exception {
        if (StringUtils.isNotBlank(ids)){
            Map<String,Object> map = new HashMap<String, Object>(4);
            String[] idsArr = ids.split(",");
            map.put("ids", idsArr);
            map.put("password", SecureHandler.encrypt(UmsConstants.DEFAULT.USER_PASSWORD));
            dataService.update(UmsConstants.MAPPER.UMS_USER+".updatePasswordByIds", map);
        }
        return -1;
    }

    @Override
    public int updatePassword(String userId, String newPwd) throws Exception {
        Map<String,Object> map = new HashMap<String, Object>(4);
        map.put("ids", new String[]{userId});
        map.put("password", SecureHandler.encrypt(newPwd));
        return dataService.update(UmsConstants.MAPPER.UMS_USER+".updatePasswordByIds", map);
    }

    @Override
    public User getUserById(String userId) throws Exception {
        return (User) dataService.getObject(UmsConstants.MAPPER.UMS_USER+".getUserById", userId);
    }

    @Override
    public void perfectLoginUserInfo(User user) throws Exception {
        //获取单位信息
        List<Map<String,Object>> deptList = deptService.getDeptListByUserId(user.getId());
        if(deptList != null && deptList.size() > 0){
            StringBuilder sbId = new StringBuilder();//单位id
            StringBuilder sbName = new StringBuilder();//单位名称
            for (int i=0;i<deptList.size();i++){
                if(i != 0){
                    sbId.append(",");
                    sbName.append(",");
                }
                sbId.append(deptList.get(i).get("ID"));
                sbName.append(deptList.get(i).get("NAME"));
            }
            user.setDeptId(sbId.toString());//将单位信息赋给user
            user.setDeptName(sbName.toString());
        }
        //获取角色信息
        List<Map<String,Object>> roleList = roleService.getRoleListByUserId(user.getId());
        if(roleList != null && roleList.size() > 0){
            StringBuilder sbId = new StringBuilder();//角色id
            StringBuilder sbName = new StringBuilder();//角色名称
            StringBuilder sbRange = new StringBuilder();//管理范围
            for (int i=0;i<roleList.size();i++){
                if(i != 0){
                    sbId.append(",");
                    sbName.append(",");
                    sbRange.append(",");
                }
                sbId.append(roleList.get(i).get("ID"));
                sbName.append(roleList.get(i).get("NAME"));
                sbRange.append(roleList.get(i).get("RANGE_ID"));
            }
            user.setRoleId(sbId.toString());//将角色信息赋给user
            user.setRoleName(sbName.toString());

            //设置用户管理范围
            String rangeId = sbRange.toString();
            if(rangeId != null && rangeId.length() > 0){
                String[] rangeArr = rangeId.split(",");
                user.setRangeId(deptService.getMaxRangeId(rangeArr));
            }
        }
    }

    @Override
    public List<User> getUserListByCompanyId(String companyId) throws Exception {
        return dataService.getList(UmsConstants.MAPPER.UMS_USER+".getUserListByCompanyId", companyId);
    }

    //判断用户id或account是否被使用
    @Override
    public boolean existUserIdOrAccount(String userIdOrAccount) throws Exception {
        Integer count = (Integer)dataService.getObject(UmsConstants.MAPPER.UMS_USER + ".countUserByUserIdOrAccount", userIdOrAccount);
        if (count != null && count > 0){
            return true;
        }
        return false;
    }
}
